package utils

import (
	"crypto/rand"
	"log"
	"math/big"
)

var (
	DefaultRandomLength = 8
)

func getRandomNum() int {
	bg := big.NewInt(1e8)
	n, err := rand.Int(rand.Reader, bg)
	if err != nil {
		log.Println(err)
		return 0
	}
	// add n to min to support the passed in range
	return int(n.Int64())
}

func GetRandomRangeNum(min int, max int) int {
	if min == max {
		return min
	}
	bg := big.NewInt(int64(max - min))
	n, err := rand.Int(rand.Reader, bg)
	if err != nil {
		log.Println(err)
		return 0
	}
	// add n to min to support the passed in range
	return min + int(n.Int64())
}

func GetRandomString(minLength int, maxLength int, pre string, suf string, enumData []string) string {

	if len(enumData) > 0 {
		return pre + getRandomEnumString(enumData) + suf
	}

	return getRandomRangePreString(minLength, maxLength, pre, suf)

}

func getRandomRangePreString(minLength int, maxLength int, pre string, suf string) string {
	return pre + createRandomString(maxLength-minLength) + suf

}
func getRandomEnumString(enumData []string) string {
	return enumData[getRandomNum()%len(enumData)]
}

func createRandomString(n int) string {
	if n == 0 {
		return ""
	}
	var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	le := int64(len(letterRunes))
	b := make([]rune, n)
	for i := range b {
		bigInt := big.NewInt(le)
		randomInt, _ := rand.Int(rand.Reader, bigInt)
		b[i] = letterRunes[randomInt.Int64()%le]
	}
	return string(b)
}

func GetRandomStringInt(min int, max int, pre string, suf string) string { // todo  pre目前不包含于长度之中
	var (
		letterRunes = []rune("1234567890")
		dataLength  int
	)
	if min == 0 && max == 0 {
		dataLength = DefaultRandomLength
	} else if min == max {
		dataLength = min
	} else {
		dataLength = getRandomNum()%(max-min) + min
	}
	le := int64(len(letterRunes))
	b := make([]rune, dataLength)
	for i := range b {
		bigInt := big.NewInt(le)
		randomInt, _ := rand.Int(rand.Reader, bigInt)
		b[i] = letterRunes[randomInt.Int64()%le]
	}
	if min > 0 {
		return pre + string(b[:min]) + suf
	}
	return pre + string(b) + suf
}
